/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hello;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Vector;
import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DataElement;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Gauge;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.*;

/**
 * @author leonaaaardo
 */
public class ClienteBT extends MIDlet implements CommandListener,DiscoveryListener {

    public static final UUID SERVICIO_CHAT = new UUID(0x2345);
    public static final int atributoSaludo = 0x1111;
    public static final UUID[] SERVICIOS =
        new UUID[]{ SERVICIO_CHAT };
public static final int[] ATRIBUTOS =
        new int[]{ atributoSaludo };
        private LocalDevice localDevice = null;
    private Command comenzar;
    private Command cancelar;
   private TextBox texto;
    private List opciones;
    private Form principal;
    private DiscoveryAgent discoveryAgent;
    private Vector busquedas;
    private Command send;
    private List serv;
    private ServiceRecord[] services;
    public void startApp() {
       texto = new TextBox("El servidor te dice...",
"", 50, TextField.UNEDITABLE);
        busquedas = new Vector();
        opciones = new List("Servicios descubiertos",List.IMPLICIT);
        serv = new List("Servicios ",List.IMPLICIT);
        comenzar = new Command("Buscar", Command.ITEM, 1);
        cancelar = new Command("Cancelar", Command.ITEM, 1);
        send = new Command("Send",Command.ITEM,1);
        principal = new Form("Busqueda de servicio");
        principal.append(new Gauge("Buscando servicio...",false, Gauge.INDEFINITE,Gauge.CONTINUOUS_RUNNING));
        principal.addCommand(cancelar);
        principal.setCommandListener(this);
        opciones.addCommand(comenzar);
       opciones.addCommand(send);
        opciones.setCommandListener(this);
        
        
try {
         localDevice = LocalDevice.getLocalDevice();
         localDevice.setDiscoverable(DiscoveryAgent.GIAC);
         discoveryAgent = localDevice.getDiscoveryAgent();
         Display.getDisplay(this).setCurrent(opciones);
} catch(Exception e) {
         e.printStackTrace();
         Alert alert = new Alert("Error",
                 "No se puede hacer uso de Bluetooth",
                 null, AlertType.ERROR);
         Display.getDisplay(this).setCurrent(alert);
}


    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    public void commandAction(Command c, Displayable d) {
        if (c == comenzar) {
        comenzar();
        }
        if( c == cancelar) {
        cancelar();
        }
        if(c==send)
        {   new Thread(new Runnable(){
public void run()
{
try{
enviarMensaje();
}catch(Exception e){}
}
}).start();
        }


    }

   


    private void comenzar() {
        try {
        discoveryAgent.startInquiry(
                DiscoveryAgent.GIAC, this);
        Display.getDisplay(this).setCurrent(opciones);
} catch(BluetoothStateException e) {
        e.printStackTrace();
        Alert alert = new Alert("Error",
                "No se pudo comenzar la busqueda",
                null, AlertType.ERROR);
        Display.getDisplay(this).setCurrent(alert);
}

    }
   private void cancelar() {
        discoveryAgent.cancelInquiry(this);
        Enumeration en = busquedas.elements();
        Integer i;
        while(en.hasMoreElements()) {
                 i = (Integer) en.nextElement();
                 discoveryAgent.cancelServiceSearch(i.intValue());
        }
}
//metodos de la interfaz DiscoveryListener
public void deviceDiscovered(RemoteDevice remoteDevice,
        DeviceClass deviceClass) {
        String address = remoteDevice.getBluetoothAddress();
        String friendlyName = null;
        try {
                 friendlyName = remoteDevice.getFriendlyName(true);
        } catch(IOException e) { }
        String device = null;
        if(friendlyName == null) {
                 device = address;
        } else {
                 device = friendlyName + " ("+address+")";
        }
        try {
                 int transId =
                         discoveryAgent.searchServices(ATRIBUTOS,
                         SERVICIOS, remoteDevice, this);
                 System.out.println("Comenzada busqueda"+
                         " de serivicios en: "+device+"; "+transId);
                 busquedas.addElement(new Integer(transId));
        } catch(BluetoothStateException e) {
                 e.printStackTrace();


                   System.err.println("No se pudo "+
                              "comenzar la busqueda");
          }
  }
  public void inquiryCompleted(int discType) {
          switch(discType) {
                   case DiscoveryListener.INQUIRY_COMPLETED:
                              System.out.println("Busqueda "+
                              "de dispositivos concluida "+
                              "con normalidad");
                   break;
                   case DiscoveryListener.INQUIRY_TERMINATED:
                              System.out.println("Busqueda "+
                              "de dispositivos cancelada");
                   break;
                   case DiscoveryListener.INQUIRY_ERROR:
                              System.out.println("Busqueda"+
                              " de dispositivos finalizada "+
                              "debido a un error");
                   break;
          }
          
  }

  public void serviceSearchCompleted(int transID, int respCode) {
          System.out.println("Busqueda de servicios "+transID+
                   " completada");
          switch(respCode) {
                   case DiscoveryListener.SERVICE_SEARCH_COMPLETED:
                   System.out.println("Busqueda completada "+
                              "con normalidad");
                   break;
                   case DiscoveryListener.SERVICE_SEARCH_TERMINATED:
                   System.out.println("Busqueda cancelada");
                   break;
              case DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
                   System.out.println("Dispositivo no alcanzable");
                   break;
                   case DiscoveryListener.SERVICE_SEARCH_NO_RECORDS:
                   System.out.println("No se encontraron registros"+
                              " de servicio");
                   break;
                   case DiscoveryListener.SERVICE_SEARCH_ERROR:
                   System.out.println("Error en la b#squeda");
                   break;
          }
  }

  private  synchronized void enviarMensaje()
  {


  String url = services[opciones.getSelectedIndex()].getConnectionURL(
ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
  StreamConnection connection = null;
DataInputStream in = null;
DataOutputStream out = null;
System.out.println("salud" + url);
try {
connection =
(StreamConnection) Connector.open(url);
in = connection.openDataInputStream();
out = connection.openDataOutputStream();
out.writeUTF("saludos desde el cliente: " + localDevice.getBluetoothAddress()  );
out.flush();
/*String s = in.readUTF();
texto.setString(s);
Display.getDisplay(this).setCurrent(texto);*/
cancelar(); //cancelamos las busquedas
} catch(IOException e) {
e.printStackTrace();
} finally {
try {
if(in != null)
in.close();
if(out != null)
out.close();
if(connection != null)
connection.close();
} catch(IOException e) {e.printStackTrace();}
}

  }
  public void servicesDiscovered(int transID,
ServiceRecord[] servRecord) {
ServiceRecord service = null;
services = new ServiceRecord[servRecord.length];
for(int i=0; i<servRecord.length; i++){
services[i] = servRecord[i];


            try {String url;
                url = services[i].getHostDevice().getFriendlyName(true);
                opciones.append(url, null);
            } catch (IOException ex) {
                ex.printStackTrace();
            }

}

  }

}


